import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { JoinRoomMessageData } from "../types/MessageData";

export const joinRoomHandler = ({ user, payload, client }: { client: WebSocket; user: User; payload: JoinRoomMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	if (room) {
		const player = room?.players.find((v) => v.user.userId == user.userId);
		if (!player) {
			room.players.push({
				user: user,
				dead: false,
				heros: [],
				currentHerosSkinId: [],
				hiddenHeroIds: [],
				healthLimit: 0,
				health: 0,
				skills: [],
				handCards: [],
				materielCards: [],
				delayedCards: [],
				buckleCards: [],
				marks: [],
				tied: false,
				flipped: false,
				client,
			});
		} else player.client = client;
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "joinedRoom", payload: { roomId: room.roomId, userId: user.userId } })));
		const log = { userId: user.userId, username: user.username, log: "加入了房间。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
